package com.maodou.android.ui.page.login

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.automirrored.outlined.KeyboardArrowLeft
import androidx.compose.material.icons.filled.Email
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.Lock
import androidx.compose.material.icons.sharp.CheckCircle
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.maodou.android.data.model.EmailRegisterParams
import com.maodou.android.utils.PublicUtils.isEmail
import com.maodou.android.viewmodel.login.LoginViewModel
import com.maodou.core.navigation.Navigator3
import com.maodou.core.ui.components.ActionBar
import com.maodou.core.ui.components.HSpacer
import com.maodou.core.ui.components.TitleAlignment
import com.maodou.core.ui.components.VSpacer
import com.maodou.core.ui.components.textfield.AppTextField
import com.maodou.core.ui.components.textfield.TextFieldStyles

/**
 * 注册页面 UI
 */
@Composable
fun RegisterScreen(
    viewModel: LoginViewModel = hiltViewModel()
) {
    val uiState by viewModel.uiState.collectAsStateWithLifecycle()


    var email by rememberSaveable { mutableStateOf("") }
    var verificationCode by rememberSaveable { mutableStateOf("") }
    var password by rememberSaveable { mutableStateOf("") }
    var password1 by rememberSaveable { mutableStateOf("") }
    var inviteCode by rememberSaveable { mutableStateOf("") }
    var passwordVisible by rememberSaveable { mutableStateOf(false) }

    Box(modifier = Modifier.fillMaxSize().background(Color(0xffFCFCFD))) {

        Column (modifier = Modifier.fillMaxSize().verticalScroll(rememberScrollState())) {

            LoginTopLogo()

            // 表单容器（圆角顶部，覆盖灰色区域下方）
            Surface(
                modifier = Modifier.fillMaxWidth().padding(20.dp),
                shape = RoundedCornerShape(24.dp),
                color = MaterialTheme.colorScheme.surface,
                shadowElevation = 1.dp
            ) {
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 20.dp)
                ) {
                    VSpacer(24.dp)

                    Text(
                        text = "注册",
                        style = MaterialTheme.typography.headlineSmall,
                        fontWeight = FontWeight.Bold,
                        color = MaterialTheme.colorScheme.onSurface
                    )

                    VSpacer(20.dp)

                    // 邮箱
                    AppTextField(
                        value = email,
                        onValueChange = { email = it },
                        label = "邮箱",
                        placeholder = "请输入邮箱",
                        leadingIcon = Icons.Default.Email,
                        keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(
                            keyboardType = KeyboardType.Email,
                            imeAction = ImeAction.Next
                        ),
                        colors = TextFieldStyles.filled(),
                        modifier = Modifier
                            .fillMaxWidth().height(56.dp).background(color = Color(0xffFAFAF9), shape = RoundedCornerShape(6.dp)),
                    )

                    VSpacer(10.dp)

                    // 验证码
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.spacedBy(12.dp),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        AppTextField(
                            value = verificationCode,
                            onValueChange = { verificationCode = it },
                            label = "验证码",
                            placeholder = "请输入验证码",
                            leadingIcon = Icons.Sharp.CheckCircle,
                            keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(
                                keyboardType = KeyboardType.Number,
                                imeAction = ImeAction.Next
                            ),
                            colors = TextFieldStyles.filled(),
                            modifier = Modifier
                                .weight(1f).height(56.dp).background(color = Color(0xffFAFAF9), shape = RoundedCornerShape(6.dp)),
                        )

                        Button(
                            onClick = { viewModel.onSendCode(email) },
                            enabled = isEmail(email) && !uiState.isVerificationCodeSending && uiState.timeCount == 60,
                            modifier = Modifier
                                .height(56.dp)
                                .widthIn(min = 100.dp),
                            shape = RoundedCornerShape(8.dp),
                            colors = ButtonDefaults.buttonColors(
                                containerColor = MaterialTheme.colorScheme.primary
                            )
                        ) {
                            if (uiState.isVerificationCodeSending) {
                                CircularProgressIndicator(
                                    modifier = Modifier.size(16.dp),
                                    strokeWidth = 2.dp,
                                    color = MaterialTheme.colorScheme.onSecondary
                                )
                            } else {
                                Text(
                                    text = if(uiState.timeCount == 60) "获取验证码" else "${uiState.timeCount}S重新获取",
                                    style = MaterialTheme.typography.labelMedium,
                                    color = if(uiState.timeCount == 60) MaterialTheme.colorScheme.surface else MaterialTheme.colorScheme.onSecondary
                                )
                            }
                        }
                    }

                    VSpacer(10.dp)

                    // 密码
                    AppTextField(
                        value = password,
                        onValueChange = { password = it },
                        label = "密码",
                        placeholder = "请输入密码",
                        leadingIcon = Icons.Default.Lock,
                        onTrailingIconClick = { passwordVisible = !passwordVisible },
                        singleLine = true,
                        keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(
                            keyboardType = KeyboardType.Password,
                            imeAction = ImeAction.Next
                        ),
                        visualTransformation = if (passwordVisible) VisualTransformation.None else PasswordVisualTransformation(),
                        colors = TextFieldStyles.filled(),
                        modifier = Modifier
                            .fillMaxWidth().height(56.dp).background(color = Color(0xffFAFAF9), shape = RoundedCornerShape(6.dp)),
                    )
                    VSpacer(10.dp)
                    // 密码
                    AppTextField(
                        value = password1,
                        onValueChange = { password1 = it },
                        label = "确认密码",
                        placeholder = "请再次输入密码",
                        leadingIcon = Icons.Default.Lock,
                        onTrailingIconClick = { passwordVisible = !passwordVisible },
                        singleLine = true,
                        keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(
                            keyboardType = KeyboardType.Password,
                            imeAction = ImeAction.Next
                        ),
                        visualTransformation = if (passwordVisible) VisualTransformation.None else PasswordVisualTransformation(),
                        colors = TextFieldStyles.filled(),
                        modifier = Modifier
                            .fillMaxWidth().height(56.dp).background(color = Color(0xffFAFAF9), shape = RoundedCornerShape(6.dp)),
                    )

                    VSpacer(10.dp)

                    // 邀请码（选填）
                    AppTextField(
                        value = inviteCode,
                        onValueChange = { inviteCode = it },
                        label = "邀请码（选填）",
                        placeholder = "请输入邀请码（选填）",
                        leadingIcon = Icons.Default.Favorite,
                        keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(
                            imeAction = ImeAction.Done
                        ),
                        colors = TextFieldStyles.filled(),
                        modifier = Modifier
                            .fillMaxWidth().height(56.dp).background(color = Color(0xffFAFAF9), shape = RoundedCornerShape(6.dp)),
                    )

                    VSpacer(24.dp)

                    // 注册按钮
                    Button(
                        onClick = {
                            viewModel.onRegister(EmailRegisterParams(
                                email = email,
                                code = verificationCode,
                                password = password,
                                confirmPassword = password1,
                                inviteCode = inviteCode
                            ))
                        },
                        enabled = !uiState.isLoading,
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(52.dp),
                        shape = RoundedCornerShape(12.dp)
                    ) {
                        if (uiState.isLoading) {
                            CircularProgressIndicator(
                                modifier = Modifier.size(16.dp),
                                strokeWidth = 2.dp,
                                color = MaterialTheme.colorScheme.inversePrimary
                            )
                            HSpacer(4.dp)
                            Text(text = "注册中...", textAlign = TextAlign.Center, color = MaterialTheme.colorScheme.inversePrimary)
                        } else Text(text = "注册", textAlign = TextAlign.Center)
                    }


                    VSpacer(24.dp)

                    // 底部登录引导
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(bottom = 24.dp),
                        horizontalArrangement = Arrangement.Center
                    ) {
                        Text(
                            text = "已有账号？",
                            style = MaterialTheme.typography.bodyMedium,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                        Spacer(Modifier.width(8.dp))
                        Text(
                            text = "立即登录",
                            style = MaterialTheme.typography.bodyMedium,
                            color = MaterialTheme.colorScheme.primary,
                            textDecoration = TextDecoration.Underline,
                            modifier = Modifier.clickable { Navigator3.pop() }
                        )
                    }
                }
            }
            
        }

        ActionBar(
            title = "",
            modifier = Modifier.fillMaxWidth(),
            navigationIcon = Icons.AutoMirrored.Outlined.KeyboardArrowLeft,
            onNavigationClick = {
                Navigator3.pop()
            },
            backgroundColor = Color.Transparent,
            contentColor = MaterialTheme.colorScheme.onSurfaceVariant,
            titleAlignment = TitleAlignment.Start,
        )


    }
}

@Preview(showBackground = true)
@Composable
fun RegisterScreenPreview() {
    RegisterScreen()
}